<template>
  <VPage class="app-container">
    <div class="relative" style="height: calc(100vh - 100px)">
      <CategoryWrap
        type="spu"
        @toggle="toggle"
        @nodeClick="handleNodeClick"
      ></CategoryWrap>
      <div
        class="pt-[10px]"
        :style="{ 'margin-left': isShowLeft ? containerWidth + 'px' : '0px' }"
        @keyup="handleKeyUp"
      >
        <div class="vx-table__form1 px-[8px]">
          <multi-input
            v-model="form.spu"
            placeholder="SPU"
            class="!w-[160px]"
          ></multi-input>
          <multi-input
            v-model="form.sku"
            placeholder="SKU"
            class="!w-[160px]"
          ></multi-input>
          <multi-input
            v-model="form.custom_sku"
            placeholder="自定义SKU"
            class="!w-[160px]"
          ></multi-input>
          <el-input
            v-model="form.sku_cn_title"
            placeholder="产品中文名"
            prefix-icon="search"
            clearable
            class="w-60"
          />
          <el-input
            v-model="form.custom_tag"
            placeholder="标签"
            clearable
            class="!w-[160px]"
          />
          <el-select
            v-model="form.image_for"
            placeholder="图片类型"
            clearable
            class="!w-[160px]"
          >
            <el-option
              v-for="item in options.imageForText"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-select
            v-model="form.image_source"
            placeholder="图片来源"
            clearable
            class="!w-[160px]"
          >
            <el-option
              v-for="item in options.imageSourceText"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <SelectLanguage
            class="!w-[160px]"
            v-model="form.language_id"
            placeholder="语言"
          ></SelectLanguage>
          <div class="vx-table__form-handle">
            <el-button type="primary" @click="queryForm()">查询</el-button>
            <el-button @click="resetForm()">重置</el-button>
          </div>
        </div>
        <div class="flex justify-between mx-2 px-[2px] py-[10px] form-divider">
          <div class="table-handle">
            <VButton
              auth="/goods/photo-gallery/list/upload"
              type="primary"
              @click="open()"
              ><svg-icon icon-class="add_new" />上传</VButton
            >
            <VButton auth="/goods/photo-gallery/list/delete" @click="deleteBatch()"
              ><svg-icon class="mr-1 text-red-500" icon-class="del" />删除</VButton
            >
          </div>
          <div>
            <VButton auth="/goods/photo-gallery/list/export" @click="bulkImport"
              ><i class="dk-iconfont icon-Download" />批量导入</VButton
            >
            <VButton auth="/goods/photo-gallery/list/export" @click="exportData"
              ><i class="dk-iconfont icon-Upload" />导出</VButton
            >
          </div>
        </div>
        <div class="table-auto">
          <vxe-table
            ref="tableRef"
            :height="computedHeight"
            :data="tableData"
            auto-resize
            @checkbox-change="selectChangeEvent"
            @checkbox-all="selectAllChangeEvent"
            :column-config="{ resizable: true }"
            :rowConfig="{ height: 52 }"
          >
            <vxe-column type="checkbox" width="60"></vxe-column>
            <vxe-column type="expand" width="80">
              <template #content="{ row, rowIndex }">
                <div class="image-box">
                  <template v-if="row.contents.length > 0">
                    <el-tabs
                      v-model="row.activeName"
                      class="demo-tabs"
                      @tab-click="handleClick"
                    >
                      <el-tab-pane
                        :label="item.image_type_text"
                        :name="item.image_type"
                        v-for="(item, index) in row.contents"
                        :key="index"
                      >
                        <image-list
                          :imageType="item.image_type"
                          v-model="item.values"
                          :showCheckbox="false"
                        />
                      </el-tab-pane>
                    </el-tabs>
                  </template>
                  <template v-else>
                    <el-empty description="暂无数据" />
                  </template>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="id" title="ID"></vxe-column>
            <vxe-column title="SKU">
              <template #default="{ row }">
                <VText :value="row.goods_sku?.sku" :copy="true"></VText>
              </template>
            </vxe-column>
            <vxe-column title="自定义SKU">
              <template #default="{ row }">
                <VText :value="row.goods_sku?.custom_sku" :copy="true"></VText>
              </template>
            </vxe-column>
            <vxe-column title="产品中文名">
              <template #default="{ row }">
                <VText :value="row.sku_cn_title" :copy="true"></VText>
              </template>
            </vxe-column>
            <vxe-column field="spu" title="SPU">
              <template #default="{ row }">
                <VText :value="row.spu" :copy="true"></VText>
              </template>
            </vxe-column>
            <vxe-column field="custom_tag" title="标签">
              <template #default="{ row }">
                {{ row.custom_tag || "--" }}
                <span class="text-[var(--el-color-primary)]" v-if="row.language_code"
                  >({{ row.language_code }})</span
                >
              </template>
            </vxe-column>
            <vxe-column field="update_time" title="更新时间"></vxe-column>
            <vxe-column field="operate" title="操作" width="200">
              <template #default="{ row }">
                <VButton
                  auth="/goods/photo-gallery/list/edit"
                  type="primary"
                  link
                  class="border-right mr-3"
                  @click="open(row.id)"
                  >修改</VButton
                >
                <VButton
                  auth="/goods/photo-gallery/list/push"
                  type="primary"
                  link
                  @click="pushSaiHe(row)"
                  >推送赛盒
                </VButton>
                <VButton
                  auth="/goods/photo-gallery/list/download"
                  type="primary"
                  link
                  @click="handleDownload(row)"
                  >图片下载
                </VButton>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <div class="fixed right-4 bottom-2">
          <vxe-pager
            v-model:current-page="page.pageNum"
            v-model:page-size="page.pageSize"
            :total="page.totalResult"
            :layouts="[
              'PrevJump',
              'PrevPage',
              'FullJump',
              'NextPage',
              'NextJump',
              'Sizes',
            ]"
            @page-change="pageChange"
          >
          </vxe-pager>
        </div>
      </div>
    </div>
    <edit-image ref="imageRef" @query="query"></edit-image>
    <upload-pictures ref="uploadRef"></upload-pictures>
    <el-dialog
      v-model="dialogVisible"
      title="提示"
      width="400"
      :before-close="handleClose"
    >
      <div>是否确认将SKU: {{ pushForm.sku }}的图片推送至赛盒系统</div>
      <div>
        <el-radio-group v-model="pushForm.isReplace" class="ml-4">
          <el-radio :label="0">新增</el-radio>
          <el-radio :label="1">覆盖</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer flex justify-center py-2">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="pushSaiHeConfirm" :loading="pushLoading">
            推送
          </el-button>
        </span>
      </template>
    </el-dialog>
  </VPage>
</template>
<script setup name="Photo-galleryList" lang="jsx">
import { galleryList, galleryClearning, galleryDelete, galleryPushSaiHe } from "./api";
import { getOptions, ImgDownloadTask } from "@/api/index.js";
import { computed, reactive, ref, toRefs } from "vue";
import editImage from "./components/editImage";
import UploadPictures from "./components/UploadPictures";
import ImageList from "./components/ImageList.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import CategoryWrap from "@/components/CategoryWrap";
import SelectLanguage from "@/components/Selects/SelectLanguage/index.vue";

const tableRef = ref();
const data = reactive({
  filterText: "",
  form: {
    spu: "",
    spu_cn_title: "",
    custom_tag: "",
    image_type: null,
    image_source: "",
    spu_category: "",
  },
  page: {
    pageNum: 1,
    pageSize: 10,
    totalResult: 0,
  },
  options: {
    imageForText: [],
    imageSourceText: [],
    imageTypeText: [],
  },
  tableData: [],
  records: [],
  isShowLeft: true,
  pushForm: {},
  dialogVisible: false,
  pushLoading: false,
  containerWidth: 280,
});

const {
  form,
  tableData,
  page,
  options,
  records,
  isShowLeft,
  pushForm,
  dialogVisible,
  pushLoading,
  containerWidth,
} = toRefs(data);

const computedHeight = computed(() => {
  const screenHeight = window.screen.height;
  return screenHeight - 420;
});

// 获取当前列表
const queryForm = async (pageNum = 1) => {
  try {
    const res = await galleryList({
      ...form.value,
      pageSize: page.value.pageSize,
      pageNum: pageNum,
    });
    tableData.value = res.data.map((i) => {
      i.activeName = i.contents.length > 0 && i.contents[0].image_type;
      return i;
    });
    page.value.totalResult = res.total || 1000000;
  } catch (e) {
    throw Error(e);
  }
};
const pageChange = (event) => {
  queryForm(event.currentPage);
};

const resetForm = () => {
  form.value = {
    spu: "",
    spu_cn_title: "",
    custom_tag: "",
    image_type: "",
    image_source: "",
    spu_category: "",
  };
  queryForm();
};

onMounted(() => {
  queryForm();
});

//选中菜单树
const handleNodeClick = (data) => {
  nextTick(() => {
    form.value.spu_category = data.spu_category;
    queryForm();
  });
};

// 获取
const fetchOption = () => {
  getOptions({ name: ["gallery.GoodsSkuGalleryContents"] }).then((res) => {
    options.value = res.data["gallery.GoodsSkuGalleryContents"][0];
  });
};
fetchOption();

provide("options", options);

const imageRef = ref();

// 新增、编辑
const open = (data) => {
  nextTick(() => {
    imageRef.value.open(data);
  });
};

const pushSaiHe = async (row) => {
  pushForm.value = {
    id: row.id,
    sku: row.goods_sku?.sku,
    isReplace: 0,
  };
  dialogVisible.value = true;
};

const pushSaiHeConfirm = async () => {
  pushLoading.value = true;
  try {
    const res = await galleryPushSaiHe(pushForm.value);
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    pushLoading.value = false;
  } catch (e) {
    pushLoading.value = false;
    throw Error(e);
  }
};

const handleClose = async (row) => {};

const query = () => {
  tableRef.value.handleQuery();
};
const handleClick = (event) => {};

// 一键清除
const clearing = async () => {
  const id = getRowId() || [];
  if (id.length == 0) {
    ElMessage.error("至少勾选一项");
    return;
  }
  try {
    const res = await galleryClearning({
      id,
    });
    ElMessage.success(res.message);
  } catch (e) {
    throw Error(e);
  }
};

// 删除
const deleteBatch = async () => {
  const id = getRowId() || [];
  if (id.length === 0) {
    ElMessage.error("至少勾选一项");
    return;
  }
  ElMessageBox.confirm("是否删除勾选项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
    confirmButtonClass: "btnFalses",
  }).then(async () => {
    try {
      const res = await galleryDelete({
        id,
      });
      ElMessage.success(res.message);
      queryForm();
    } catch (e) {
      throw Error(e);
    }
  });
};

// 导出
const exportData = () => {
  const id = getRowId() || [];
  if (id.length == 0) {
    ElMessage.error("至少勾选一项");
    return;
  }
  ElMessage.error("没确定方案,先别提bug");
};

const uploadRef = ref();
// 批量导入
const bulkImport = () => {
  uploadRef.value.open();
};

// 获取勾选图片id
const getRowId = () => {
  let id = [];
  if (records.value.length == 0) return false;
  records.value.forEach((i) => {
    i.contents.forEach((j) => {
      j.values.forEach((k) => {
        if (k.checked) {
          id.push(Number(k.id));
        }
      });
    });
  });
  return id;
};

const selectChangeEvent = (arr) => {
  arr.row?.contents.length &&
    arr.row.contents.forEach((i) => {
      i.values.forEach((j) => {
        j.checked = arr.checked;
      });
    });
  const $table = tableRef.value;
  if ($table) {
    records.value = $table.getCheckboxRecords();
  }
};

const selectAllChangeEvent = (arr) => {
  const $table = tableRef.value;
  if ($table) {
    records.value = $table.getCheckboxRecords();
  }
};

const handleDownload = async (row) => {
  try {
    const res = await ImgDownloadTask({
      source: 1,
      gallery_id: row.id,
    });
    ElMessage.success(
      "发起图片下载成功，请稍后前往基础管理-图片下载任务中进行图片包下载"
    );
  } catch (e) {
    throw Error(e);
  }
};

const handleKeyUp = (event) => {
  if (event.keyCode === 13 || event.key === "Enter") {
    queryForm();
    event.stopPropagation();
  }
};

const toggle = (val, width) => {
  isShowLeft.value = val;
  if (val) {
    containerWidth.value = width;
  }
};
</script>
<style scoped lang="scss">
:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background-color: transparent;

  .lable {
    color: #3487ff !important;
  }
}

.image-box {
  padding: 10px 15px;
}

.row-handle {
  display: flex;
  justify-content: flex-end;
}

.table-auto {
  padding: 0 8px 8px 8px;
  // padding-bottom: 40px;
}

:deep(.el-tabs__header) {
  margin: 0;
}
</style>
<style lang="scss">
.status {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #3a4259;
}

.enable {
  color: #3e66ee;
  width: 18px;
  height: 18px;
  margin-right: 2px;
}

.disabled {
  color: #fc6271;
  width: 18px;
  height: 18px;
  margin-right: 2px;
}

.table-handle {
  .el-button + .el-button {
    margin-left: 8px;
  }
}

.form-divider {
  .el-button {
    height: 28px;
  }
}

.vx-table__form {
  padding-bottom: 10px !important;
}
.vx-table__form1 {
  display: flex;
  gap: 8px;
  position: relative;
  padding-bottom: 10px;
}
.vx-table__form1::before {
  content: "";
  position: absolute;
  bottom: 0;
  left: 80px;
  right: 80px;
  height: 1px;
  background-image: linear-gradient(
    to right,
    rgba(153, 153, 153, 0.15) 35%,
    transparent 0%
  );
  background-repeat: repeat-x;
  background-size: 16px 1px;
  background-position: 10px bottom;
}
</style>
